//
//  WBTabBar.swift
//  weibobo
//
//  Created by KIMI on 16/9/19.
//  Copyright © 2016年 KIMI. All rights reserved.
//

import UIKit
//定义代理协议
protocol WBTabarDelegate: NSObjectProtocol{
    //代理方法
    func didSelectedComposeBrn()
}
class WBTabBar: UITabBar {
    
    //点击撰写按钮执行的闭包
    var composeBtnClosure :(()->())?
    
    //代理
    weak var WBDelegate: WBTabarDelegate?
    
    //懒加载创建中间按钮
        lazy var composeButton: UIButton = {
        
        let button = UIButton()
            
        //添加撰写按钮的点击事件
            button.addTarget(self, action: #selector(composeButtonAction), for: .touchUpInside)
        //设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .normal)
            
       
         
        button.sizeToFit()
            
        return button
    }()

    override init(frame: CGRect) {

        super.init(frame: frame)
        
        self.backgroundImage = UIImage(named: "tabbar_background")
        setupUI()
    }
    
    //撰写按钮的点击事件
    @objc private func composeButtonAction() {
//        print("ddd")
        
        //回调闭包
        composeBtnClosure!()
        
        //实现代理方法
        WBDelegate?.didSelectedComposeBrn()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    func setupUI()  {
        
        addSubview(composeButton)
    }
    //重写layoutSubviews方法 设置子控件的位置
    override func layoutSubviews() {
        
        super.layoutSubviews()
        //设置撰写按钮的位置
        composeButton.centerX = width / 2
        composeButton.centerY = height / 2
        
        //计算每一个按钮的宽度
        let itemWidth = width / 5
        
        //记录遍历到第几个按钮的索引
        var index = 0
        
        //遍历获取系统按钮
        for value in subviews{
            
            //tabbarButton是系统私有类 不能直接获取
            if value.isKind(of: NSClassFromString("UITabBarButton")!){
                
                value.width = itemWidth
                value.x = CGFloat(index) * itemWidth
                
                index += 1
                
                if index == 2{
                    
                    index += 1
                }
                
                
            }
        }
        
    }
    
    
}



